<?php
namespace Admin\Controller;
use Lib\Api\SysMenuApi;
use Think\Controller;
use Think\Model;
class MenuController extends Controller {
    private $modelName = 'SysMenu';

    public function index(){
        $this->display();
    }

    public function tolist() {
        $page_size = $_POST['page_size'];
        $page_num = $_POST['page_num'];
        $keyword = $_POST['keyword'];
        $pid = $_POST['pid'];

        if ($keyword <> "")
            $map['name'] = array('like', '%'.$keyword.'%');
        $map['pid'] = array('eq', $pid);


        $list = SysMenuApi::getList($map, $page_num, $page_size, '*', 'sort asc');
        $total = SysMenuApi::getTotal($map);

        $data = pageHelper($page_size, $page_num, $list, $total);
        $this->ajaxReturn($data);
    }

    public function delete() {
        $map['id'] = $_POST['id'];
        SysMenuApi::delete($map);

        $data['code'] = 0;
        $this->ajaxReturn($data);
    }

    public function changeState() {
        $modelObj = M($this->modelName);
        $this->ajaxReturn(SysMenuApi::save($modelObj->create($_POST, Model::MODEL_UPDATE)));
    }

    public function addoredit() {
        $data = SysMenuApi::getInfo(array('id' => $_GET['id']));
        //$data['id'] = 1;
        $this->assign('data', $data);
        $this->display();
    }

    public function addoreditdata() {
        $modelObj = M($this->modelName);
        $ajaxdata['code'] = 0;
        if (empty($_POST['id'])) {
            $data = $modelObj->create($_POST);
            //数据校验
            if (empty($data['name'])) {
                $ajaxdata['code'] = -1;
                $ajaxdata['msg'] = '未填写菜单名称';
                $this->ajaxReturn($ajaxdata);
            }

            //添加的数据是否存在
            $result = SysMenuApi::getTotal(array('name' => $data['name']));
            if ($result == 0) {
                //数据不存在，添加数据
                SysMenuApi::add($data);
                $ajaxdata['msg'] = '添加成功';
            } else {
                $ajaxdata['code'] = -1;
                $ajaxdata['msg'] = '添加失败，菜单已存在';
            }
        } else {
            $modelObj = M($this->modelName);
            $data = $modelObj->create($_POST);
            SysMenuApi::save($data);
            $ajaxdata['msg'] = '修改成功';
        }

        $this->ajaxReturn($ajaxdata);
    }

    public function getParentMenu() {
        $map['pid'] = 0;
        $list = SysMenuApi::getList($map, 1, 999999);
        $this->ajaxReturn($list);
    }
}